package com.lmxdawn.api.dnf.controller;

import com.lmxdawn.api.admin.entity.auth.AuthAdmin;
import com.lmxdawn.api.admin.service.auth.AuthAdminService;
import com.lmxdawn.api.common.res.BaseResponse;
import com.lmxdawn.api.common.session.SessionContextHolder;
import com.lmxdawn.api.common.util.ResultVOUtils;
import com.lmxdawn.api.dnf.annotation.LoginIgnore;
import com.lmxdawn.api.dnf.dto.CommonReq;
import com.lmxdawn.api.dnf.dto.request.LoginReq;
import com.lmxdawn.api.dnf.dto.response.LoginResp;
import com.lmxdawn.api.dnf.service.IWebLoginService;
import com.lmxdawn.api.dnf.util.RequestUtil;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * web端用户登录
 */
@RestController
@RequestMapping("/web/auth")
public class WebLoginController {

	@Resource
	private IWebLoginService loginService;

	@Resource
	private AuthAdminService authAdminService;

	/**
	 * 账户密码登录
	 */
	@LoginIgnore
	@PostMapping("/login")
	public BaseResponse<LoginResp> login(@RequestBody @Valid CommonReq<LoginReq> loginReq) {
		LoginResp loginResp = loginService.login(loginReq.getContent());
		return ResultVOUtils.success(loginResp);
	}

	/**
	 * 发送验证码
	 */
	@LoginIgnore
	@PostMapping("/send-phone-code")
	public BaseResponse<String> sendPhoneCode(@RequestBody @Valid CommonReq<LoginReq> loginReq) {
		loginService.sendPhoneCode(loginReq.getContent());
		return ResultVOUtils.success();
	}

	/**
	 * 手机验证码登录
	 */
	@LoginIgnore
	@PostMapping("/phone-code-login")
	public BaseResponse<LoginResp> phoneCodeLogin(HttpServletRequest request, @RequestBody @Valid CommonReq<LoginReq> loginReq) {
		Assert.hasLength(loginReq.getContent().getPhoneCode(), "验证码不能为空");
		LoginReq content = loginReq.getContent();
		content.setType(RequestUtil.getRequestType(request));
		LoginResp loginResp = loginService.phoneCodeLogin(content);
		return ResultVOUtils.success(loginResp);
	}

	/**
	 * 获取当前用户基本信息
	 *
	 * @return
	 */
	@PostMapping("/get-user-info")
	public BaseResponse<AuthAdmin> getUserInfo() {
		String userId = SessionContextHolder.getId();
		AuthAdmin authAdmin = authAdminService.findById(userId);
		return ResultVOUtils.success(authAdmin);
	}

	@PostMapping("/log-out")
	public BaseResponse<String> logOut(HttpServletRequest request, HttpServletResponse response) {
		loginService.logOut(request, response);
		return ResultVOUtils.success();
	}
}
